package org.home.base.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.home.sys.bean.SysUser;
import org.home.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by nanshouxiao on 2017/7/29 16:01.
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * session存储用户的key
     */
    public static final String SYS_USER_KEY = "sysUser";

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SecurityUtils.getSubject().getSession().getAttribute(SYS_USER_KEY);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        SysUser user = tokenToUser((UsernamePasswordToken) authenticationToken);
        SysUser storeUser = sysUserService.getEntityByEntity(user);
        if(storeUser != null && user.getPassword().equals(storeUser.getPassword())){
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute(SYS_USER_KEY, storeUser);

            Object principal = authenticationToken.getPrincipal();
            return new SimpleAuthenticationInfo(principal, user.getPassword(), this.getName());
        }
        return null;
    }

    private SysUser tokenToUser(UsernamePasswordToken token) {
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        return new SysUser(username, password);
    }
}

